 <template>
    <div>
        <div class="common-title">
            <h3>提交评论</h3>
            <p>返回</p>
        </div>
        <div class="text">
            <textarea v-model='newComment'></textarea>
        </div>

        <div class="btn">
            <mt-button type="primary" @click='sendMsg'>发表评论</mt-button>
        </div>
        <div class="common-title">
            <h3>评论列表</h3>
            <p>0条评论</p>
        </div>
        <ul>
            <li v-for='item in msg'>{{item.user_name}} {{item.content}} {{item.add_time | relativeTime}}</li>
        </ul>
        <div class="btn">
            <mt-button type="danger" @click='getCommon(page)' plain>加载更多{{page}}</mt-button>
        </div>
    </div>
</template>
<script>
    export default {
        name: 'common',
        props: ['cid'],
        data () {
            return {
                msg: [],
                page: 1,
                newComment: ''
            }
        },
        created () {
            this.page = this.$route.query.page || '1';
            this.$nextTick( () => {
                this.getCommon();
            })
        },
        methods: {
            getCommon(page){
                this.$axios.get(`${process.env.API_HOST}/getcomments/${this.cid}?pageindex=${this.page}`)
                .then(res => {
                    if(page){
                        this.msg = this.msg.concat(res.data.message);
                        this.page ++;
                    }else{
                        this.msg = res.data.message;
                    }
                })
                .catch(err => console.log("err"))
            },
            sendMsg(){
                if( this.newComment.trim() === ''){
                    this.$toast('请输入评论内容');
                    return false
                }
                this.$axios.post(process.env.API_HOST + 'postcomment/' + this.cid,'content=' + this.newComment)
                .then(res => {
                    this.newComment = '';
                    this.page = 1;
                    this.$toast('评论成功');
                    this.getCommon();
                })
                .catch(err => console.log("评论失败"))
            }
        }
    }
</script>
<style scoped="">
    .common-title{
        width: 100%;
        display: flex;
        padding: 0 10px;
        justify-content: space-between;
    }
    .text{
        width: 100%;
        padding: 0 10px;
    }
    textarea{
        width: 100%;
        height: 40px;
    }
    .btn {
        width: 100%;
        padding: 0 10px;
    }
    .btn >>> button{
        width: 100%;
    }
    ul{
        padding: 10px;
    }
    li{
        height: 30px;
        line-height: 30px;
        border-bottom: 1px solid #ccc;
    }
</style>